package com.safe.first.infrastructure.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.safe.first.common.model.R;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mickey
 * @since 2022/6/12
 **/
@Component
@RequiredArgsConstructor
public class MyHttp403ForbiddenEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2)
            throws IOException {
        response.setHeader("Content-Type", "application/json");
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.getWriter().write(objectMapper.writeValueAsString(R.ofError(arg2.getMessage())));
    }
}
